import util from "./util.js";
import { userLogin } from '@/api/user'

export const wxUtil = {
  async getJsCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: async (res) => {
          if (res.code) {
            resolve(res.code)
          } else {
            reject(res.errMsg)
          }
        }
      })
    })
  },
  async wxLogin(force) {
    const jsCode = await wxUtil.getJsCode();
    return new Promise((resolve, reject) => {
      wxUtil.yjyWxLogin(jsCode).then(() => resolve(true), async res => {
        if (force && !util.getFullPagePath().startsWith("/pages/common/login/login")) {
          await uni.confirm("您还未登录小程序,前先登录")
          uni.redirectTo({
            url: "/pages/common/login/login?targetUrl=" + encodeURIComponent(util.getFullPagePath())
          })
          // && res.msg !== "用户不存在" && uni.toast('登录过期,请重新登录');
        }
        reject(false)
      });
    })
  },

  async yjyWxLogin(appId,jsCode, mobile = null, iv = null) {
    // if (uni.getStorageSync('requestHeader').Authorization) return true;
    let data = {
      clientType: 2,
      loginType: 0,
      jsCode,
      mobile,
      iv,
    }
    userLogin(appId, data).then(res => {
      console.log(res);
      // 获取系统型号
      uni.getSystemInfo({
        success:function(e){
          res.devAgent = e.system.split(' ')[0];
        }
      })
      if (!res) return Promise.reject(res)
      let { data } = res.data;
      let requestHeader = {
        Authorization: `Bearer ${data.token}`, //token
        userId: data.userId,
        devAgent:data.devAgent,
      }
      uni.setStorageSync('requestHeader', requestHeader)
      let userInfo = {
        wxNickname:data.wxNickname || '',
        userMobile: data.mobile,
        userId: data.userId,
        avatarUrl:data.avatarUrl || '',
      }
      uni.setStorageSync('userInfo', userInfo)
      return Promise.resolve(res);
    }).catch(e => {
      return Promise.reject(e)
    })
  },

  
}

